package com.example.customizedgroupmessage;

import java.util.ArrayList;

import com.example.customizedgroupmessage.SMSSendActivity.SMSThread;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.*;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.text.*;
import android.text.style.*;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

public class SMSMemberListView extends Activity {
	// 요청코드
	public static final int REQUEST_CODE_SMSTEMPLATE=1003;
	protected static final int REQUEST_CODE_SMSGROUPLISTVIEW = 0;
	// Log TAG
	//private static final String TAG2 = "Member TAG";

	public int receiverCount = 0;
	boolean isSearching = false;

	String selectedGroup = null;
	String selectedGroupId = null;
	ArrayList<Contact> arrContact = new ArrayList<Contact>();
	ArrayList<Contact> arrContactSearch = new ArrayList<Contact>();
	ContactsAdapter Adapter;
	DBHelper mHelper;
	SQLiteDatabase db;
	getContactThread mThread;
	ListView list;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_member_listview);

		// 선택된 그룹 이름, id 받아오기
		Intent intent = getIntent();
		selectedGroup = intent.getStringExtra("SelectedGroup");
		selectedGroupId = intent.getStringExtra("SelectedGroupId");
		if (selectedGroup != null){
			super.setTitle(selectedGroup);
		}

		// sms db 생성
		mHelper = new DBHelper(this);

		arrContact.clear();

		// 어댑터 준비
		Adapter = new ContactsAdapter(this, R.layout.sms_member, arrContact);

		// 리스트뷰에 어탭터 연결
		list = (ListView)findViewById(R.id.sms_member_list);
		list.setAdapter(Adapter);
		Adapter.notifyDataSetChanged();
		
		// contact2.db로부터 연락처 가져오기
		mThread = new getContactThread();
		mThread.setDaemon(true);
		mThread.start();


		// 이벤트 핸들러 연결
		list.setOnItemClickListener(mItemClickListener);


		// 검색
		final EditText editSearch = (EditText)findViewById(R.id.editSearch);
		Button btnSearch = (Button)findViewById(R.id.btnSearch);
		btnSearch.setVisibility(View.GONE); // 취소버튼 숨김

		editSearch.addTextChangedListener(textWatcherInput); //텍스트가 변할때 이벤트
		editSearch.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// 버튼 보이기
				Button btnSearch = (Button)findViewById(R.id.btnSearch);
				btnSearch.setVisibility(View.VISIBLE);
			}
		});

		btnSearch.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// 검색창 내용 지우기
				editSearch.setText("");
				editSearch.setHint("이름 검색");
				// 키보드 내리기
				InputMethodManager mgr = (InputMethodManager)getSystemService(SMSMemberListView.INPUT_METHOD_SERVICE);
				mgr.hideSoftInputFromWindow(editSearch.getWindowToken(), 0);
				// 버튼 숨기기
				Button btnSearch = (Button)findViewById(R.id.btnSearch);
				btnSearch.setVisibility(View.GONE);
			}
		});


		//선택된 수신자 수 받아오기
		receiverCount = getReceiverCount();
		TextView textReceiverCount = (TextView)findViewById(R.id.textReceiverCount);
		textReceiverCount.setText("총 "+receiverCount+"명의 수신자");
		textReceiverCount.setGravity(Gravity.RIGHT);
		//목록 보기
		Button btnSeeReceiverList = (Button)findViewById(R.id.btnSeeReceiverList);
		btnSeeReceiverList.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				AlertDialog dialog = createDialogBox();
				dialog.show();
			}
		});

		// 하단 버튼
		//이전
		Button btnMoreSelect = (Button)findViewById(R.id.btnMoreSelect);
		btnMoreSelect.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// 이 액티비티를 시작하게 한 인텐트를 호출한다.
				Intent intent = getIntent();
				setResult(RESULT_OK, intent); // 인텐트를 반환한다.
				finish(); // 액티비티 종료
			}
		});
		//전체선택
		Button btnAllSelect = (Button)findViewById(R.id.btnAllSelect);
		btnAllSelect.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				db = mHelper.getWritableDatabase();
				String _id, name, status, organization, phone, group = null;
				
				if(isSearching){
					for (int i=0; i<arrContactSearch.size(); i++){
						if (arrContactSearch.get(i).isChecked) { //이미 체크된 항목은 pass
							continue;
						}
						else {
							arrContactSearch.get(i).setChecked(); //체크박스에 체크

							_id = arrContactSearch.get(i).getId();
							name = arrContactSearch.get(i).getName();
							status = arrContactSearch.get(i).getStatus();
							organization = arrContactSearch.get(i).getOrganization();
							phone = arrContactSearch.get(i).getPhone();
							group = arrContactSearch.get(i).getGroup();

							//DB에 쓰기
							if (status != null && organization != null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', '"+organization+"', '"+phone+"', '"+group+"', null, null);");
							}
							else if (organization != null && status == null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, '"+organization+"', '"+phone+"', '"+group+"', null, null);");
							}
							else if (organization == null && status != null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', null, '"+phone+"', '"+group+"', null, null);");
							}
							else {
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, null, '"+phone+"', '"+group+"', null, null);");
							}

							_id = null;
							name = null;
							status = null;
							organization = null;
							phone = null;
						}
					}
				}
				else{
					for (int i=0; i<arrContact.size(); i++){
						if (arrContact.get(i).isChecked) { //이미 체크된 항목은 pass
							continue;
						}
						else {
							arrContact.get(i).setChecked(); //체크박스에 체크

							_id = arrContact.get(i).getId();
							name = arrContact.get(i).getName();
							status = arrContact.get(i).getStatus();
							organization = arrContact.get(i).getOrganization();
							phone = arrContact.get(i).getPhone();
							group = arrContact.get(i).getGroup();

							//DB에 쓰기
							if (status != null && organization != null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', '"+organization+"', '"+phone+"', '"+group+"', null, null);");
							}
							else if (organization != null && status == null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, '"+organization+"', '"+phone+"', '"+group+"', null, null);");
							}
							else if (organization == null && status != null){
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', null, '"+phone+"', '"+group+"', null, null);");
							}
							else {
								db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, null, '"+phone+"', '"+group+"', null, null);");
							}

							_id = null;
							name = null;
							status = null;
							organization = null;
							phone = null;
						}
					}
				}
				mHelper.close();

				//선택된 수신자 수 받아오기
				receiverCount = getReceiverCount();
				TextView textReceiverCount = (TextView)findViewById(R.id.textReceiverCount);
				textReceiverCount.setText("총 "+receiverCount+"명의 수신자");

				// 리스트뷰 목록 화면 갱신
				Adapter.notifyDataSetChanged();
			}
		});
		//전체 해제
		Button btnAllCancel = (Button)findViewById(R.id.btnAllCancel);
		btnAllCancel.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				db = mHelper.getWritableDatabase();
				String _id = null;
				
				if(isSearching){
					for (int i=0; i<arrContactSearch.size(); i++){
						if (arrContactSearch.get(i).isChecked == false) { //체크 안 된 항목은 pass
							continue;
						}
						else {
							arrContactSearch.get(i).setUnchecked(); //체크박스에 체크 해제
							_id = arrContactSearch.get(i).getId();

							//DB에서 삭제
							db.execSQL("DELETE FROM sms WHERE _id = "+_id+";");

							_id = null;
						}
					}
				}
				else{
					for (int i=0; i<arrContact.size(); i++){
						if (arrContact.get(i).isChecked == false) { //체크 안 된 항목은 pass
							continue;
						}
						else {
							arrContact.get(i).setUnchecked(); //체크박스에 체크 해제
							_id = arrContact.get(i).getId();

							//DB에서 삭제
							db.execSQL("DELETE FROM sms WHERE _id = "+_id+";");

							_id = null;
						}
					}
				}
				mHelper.close();

				//선택된 수신자 수 받아오기
				receiverCount = getReceiverCount();
				TextView textReceiverCount = (TextView)findViewById(R.id.textReceiverCount);
				textReceiverCount.setText("총 "+receiverCount+"명의 수신자");

				// 리스트뷰 목록 화면 갱신
				Adapter.notifyDataSetChanged();
			}
		});
		//다음
		Button btnSMSCheckNext = (Button)findViewById(R.id.btnSMSCheckNext);
		btnSMSCheckNext.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				Intent intent = new Intent(getBaseContext(), SMSTemplate.class);
				startActivityForResult(intent, REQUEST_CODE_SMSTEMPLATE);
			}
		});

	}


	// 리스트뷰 OnClick 이벤트 핸들러
	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			db = mHelper.getWritableDatabase();
			Cursor cursor;

			if(isSearching){
				String _id = arrContactSearch.get(position).getId();
				String name = arrContactSearch.get(position).getName();
				String status = arrContactSearch.get(position).getStatus();
				String organization = arrContactSearch.get(position).getOrganization();
				String phone = arrContactSearch.get(position).getPhone();
				String group = arrContactSearch.get(position).getGroup();
				boolean isExist = false;

				// 체크박스 선택/해제
				if(arrContactSearch.get(position).isChecked){
					arrContactSearch.get(position).setUnchecked();
				}
				else{
					arrContactSearch.get(position).setChecked();
				}

				// 체크되면 DB에 저장
				if (arrContactSearch.get(position).isChecked) {
					cursor = db.rawQuery("SELECT _id FROM sms", null);
					while (cursor.moveToNext()) {
						if (_id.equals(cursor.getString(0))) {
							isExist = true;
						}
					}
					cursor.close();

					if (isExist) {
						//Toast toast = Toast.makeText(getApplicationContext(), "이미 선택된 연락처입니다.", Toast.LENGTH_SHORT);
						//toast.show();
					}
					else {
						if (status != null && organization != null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', '"+organization+"', '"+phone+"', '"+group+"', null, null);");
						}
						else if (organization != null && status == null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, '"+organization+"', '"+phone+"', '"+group+"', null, null);");
						}
						else if (organization == null && status != null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', null, '"+phone+"', '"+group+"', null, null);");
						}
						else {
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, null, '"+phone+"', '"+group+"', null, null);");
						}
					}

					// 원본에서 체크 설정
					for(int i=0; i<arrContact.size(); i++){
						if(_id.equals(arrContact.get(i).getId())){
							arrContact.get(i).setChecked();
						}
					}
				}
				// 체크해제되면 DB에서 삭제
				else {
					db.execSQL("DELETE FROM sms WHERE _id = "+_id+";");

					// 원본에서 체크 해제
					for(int i=0; i<arrContact.size(); i++){
						if(_id.equals(arrContact.get(i).getId())){
							arrContact.get(i).setUnchecked();
						}
					}
				}
			}

			else {		
				String _id = arrContact.get(position).getId();
				String name = arrContact.get(position).getName();
				String status = arrContact.get(position).getStatus();
				String organization = arrContact.get(position).getOrganization();
				String phone = arrContact.get(position).getPhone();
				String group = arrContact.get(position).getGroup();
				boolean isExist = false;

				// 체크박스 선택/해제
				if(arrContact.get(position).isChecked){
					arrContact.get(position).setUnchecked();
				}
				else{
					arrContact.get(position).setChecked();
				}

				// 체크되면 DB에 저장
				if (arrContact.get(position).isChecked) {
					cursor = db.rawQuery("SELECT _id FROM sms", null);
					while (cursor.moveToNext()) {
						if (_id.equals(cursor.getString(0))) {
							isExist = true;
						}
					}
					cursor.close();

					if (isExist) {
						//Toast toast = Toast.makeText(getApplicationContext(), "이미 선택된 연락처입니다.", Toast.LENGTH_SHORT);
						//toast.show();
					}
					else {
						if (status != null && organization != null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', '"+organization+"', '"+phone+"', '"+group+"', null, null);");
						}
						else if (organization != null && status == null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, '"+organization+"', '"+phone+"', '"+group+"', null, null);");
						}
						else if (organization == null && status != null){
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', '"+status+"', null, '"+phone+"', '"+group+"', null, null);");
						}
						else {
							db.execSQL("INSERT INTO sms VALUES ('"+_id+"', '"+name+"', null, null, '"+phone+"', '"+group+"', null, null);");
						}
					}
				}
				// 체크해제되면 DB에서 삭제
				else {
					db.execSQL("DELETE FROM sms WHERE _id = "+_id+";");
				}
			}



			mHelper.close();

			//선택된 수신자 수 받아오기
			receiverCount = getReceiverCount();
			TextView textReceiverCount = (TextView)findViewById(R.id.textReceiverCount);
			textReceiverCount.setText("총 "+receiverCount+"명의 수신자");

			// 리스트뷰 목록 화면 갱신
			Adapter.notifyDataSetChanged();
		}
	};
	
	
	Handler mHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				arrContact.add((Contact) msg.obj);
				Adapter.notifyDataSetChanged();
			}
			if (msg.what == 1) {
				Adapter.notifyDataSetChanged();
				// 이벤트 핸들러 연결
				//list.setOnItemClickListener(mItemClickListener);
			}
		}
	};

	
	class getContactThread extends Thread {
		public void run() {
			
			Contact temp;
			String id = null;
			String name = null;
			String status = null;
			String organization = null;
			String phone = null;
			String mail = null;
			String group = null;
			String groupId = null;  
			ContentResolver cr = getContentResolver();
			db = mHelper.getWritableDatabase();
			Cursor CheckCursor;
			ArrayList<String> check = new ArrayList<String>();
			boolean isExist = false;

			CheckCursor = db.rawQuery("SELECT _id FROM sms", null);
			while (CheckCursor.moveToNext()) {
				check.add(CheckCursor.getString(0));
			}
			CheckCursor.close();

			// 전체 목록일 때
			if (selectedGroupId.equals("-1")){
				Cursor cursor = cr.query(
						ContactsContract.Contacts.CONTENT_URI, null, Contacts.HAS_PHONE_NUMBER + " != 0", null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

				int ididx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
				int nameidx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

				while (cursor.moveToNext()) {
					id = cursor.getString(ididx);
					name = cursor.getString(nameidx);

					// 전화 번호는 서브 쿼리로 조사해야 함.
					Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.
							Phone.CONTENT_URI, null, 
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
									new String[]{id}, null);

					int typeidx = phoneCursor.getColumnIndex(
							ContactsContract.CommonDataKinds.Phone.TYPE);
					int numidx = phoneCursor.getColumnIndex(
							ContactsContract.CommonDataKinds.Phone.NUMBER);

					// 전화의 타입에 따라 여러 개가 존재한다.
					while (phoneCursor.moveToNext()) {
						String num = phoneCursor.getString(numidx);
						if(phoneCursor.getInt(typeidx)==ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE){
							phone = num;
						}
						else if(phoneCursor.getInt(typeidx)==ContactsContract.CommonDataKinds.Phone.TYPE_WORK){
							phone = num;
						}
					}
					phoneCursor.close();

					// 조직 정보 읽기
					Cursor statusCursor = cr.query(ContactsContract.Data.CONTENT_URI, 
							null,
							ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?",     // where
							new String[]{id, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE},  // where param 
							null);

					try {
						if (statusCursor.moveToFirst()) {
							int dataColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.DATA); 
							int typeColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.TYPE);
							int positionColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.TITLE);

							do {
								String data = statusCursor.getString(dataColumn); // 조직명
								int type = statusCursor.getInt(typeColumn);
								String position = statusCursor.getString(positionColumn); // 직급명

								if (type == ContactsContract.CommonDataKinds.Organization.TYPE_WORK){
									// 조직 정보
									if (data != null && data.length() > 0){
										organization = data;
										status = position;
									}
								}
								else {
									if (data != null && data.length() > 0){
										organization = data;
										status = position;
									}
								}

							}while(statusCursor.moveToNext());
						}
					}finally {
						statusCursor.close();
					}

					group = "";
					groupId = selectedGroupId;

					temp =  new Contact(id, name, status, organization, phone, mail, group, groupId);

					for (int i = 0; i < check.size(); i++) {
						if (id.equals(check.get(i))) {
							isExist = true;
						}
					}
					if(isExist) {
						temp.setChecked();
					}

					Message msg = mHandler.obtainMessage();
					msg.what = 0;
					msg.obj = temp;
					mHandler.sendMessage(msg);

					id = null;
					name = null;
					status = null;
					organization = null;
					phone = null;
					mail = null;
					group = null;
					groupId = null;
					isExist = false;
				}
				cursor.close();
			}

			// 그룹일 때
			else {
				groupId = selectedGroupId;
				group = selectedGroup;

				Uri uri = ContactsContract.Data.CONTENT_URI;
				String[] projection = new String[] {
						ContactsContract.CommonDataKinds.GroupMembership._ID, 
						ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME, 
						ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID, 
						ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
				};
				String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + " = " + groupId + " AND " 
						+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + " = '" 
								+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
				String[] selectionArgs = null;
				String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

				Cursor cursor = cr.query(uri, projection, selection, selectionArgs, sortOrder);

				while (cursor.moveToNext()){
					id = cursor.getString(3);
					name = cursor.getString(1);

					// 전화 번호는 서브 쿼리로 조사해야 함.
					Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.
							Phone.CONTENT_URI, null, 
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
									new String[]{id}, null);

					int typeidx = phoneCursor.getColumnIndex(
							ContactsContract.CommonDataKinds.Phone.TYPE);
					int numidx = phoneCursor.getColumnIndex(
							ContactsContract.CommonDataKinds.Phone.NUMBER);

					// 전화의 타입에 따라 여러 개가 존재한다.
					while (phoneCursor.moveToNext()) {
						String num = phoneCursor.getString(numidx);
						if(phoneCursor.getInt(typeidx)==ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE){
							phone = num;
						}
						else if(phoneCursor.getInt(typeidx)==ContactsContract.CommonDataKinds.Phone.TYPE_WORK){
							phone = num;
						}
					}
					phoneCursor.close();


					// 조직 정보 읽기
					Cursor statusCursor = cr.query(ContactsContract.Data.CONTENT_URI, 
							null,
							ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?",     // where
							new String[]{id, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE},  // where param 
							null);

					try {
						if (statusCursor.moveToFirst()) {
							int dataColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.DATA); 
							int typeColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.TYPE);
							int positionColumn = statusCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.TITLE);

							do {
								String data = statusCursor.getString(dataColumn); // 조직명
								int type = statusCursor.getInt(typeColumn);
								String position = statusCursor.getString(positionColumn); // 직급명

								if (type == ContactsContract.CommonDataKinds.Organization.TYPE_WORK){
									// 조직 정보
									if (data != null && data.length() > 0){
										organization = data;
										status = position;
									}
								}
								else {
									if (data != null && data.length() > 0){
										organization = data;
										status = position;
									}
								}

							}while(statusCursor.moveToNext());
						}
					}finally {
						statusCursor.close();
					}       

					group = selectedGroup;
					groupId = selectedGroupId;

					temp =  new Contact(id, name, status, organization, phone, mail, group, groupId);

					for (int i = 0; i < check.size(); i++) {
						if (id.equals(check.get(i))) {
							isExist = true;
						}
					}
					if(isExist) {
						temp.setChecked();
					}

					Message msg = mHandler.obtainMessage();
					msg.what = 0;
					msg.obj = temp;
					mHandler.sendMessage(msg);

					id = null;
					name = null;
					status = null;
					organization = null;
					phone = null;
					mail = null;
					group = null;
					groupId = null;
					isExist = false;
				}
				cursor.close();
			} //end else
			
			mHandler.sendEmptyMessage(1);

			// log
			/*
			for(int i=0; i<arrContact.size();i++){
				Log.d(TAG2, "Id : " + arrContact.get(i).getId());
				Log.d(TAG2, "Name : " + arrContact.get(i).getName());
				Log.d(TAG2, "Status : " + arrContact.get(i).getStatus());
				Log.d(TAG2, "Organization : " + arrContact.get(i).getOrganization());
				Log.d(TAG2, "Phone : " + arrContact.get(i).getPhone());
				Log.d(TAG2, "Mail : " + arrContact.get(i).getMail());
				Log.d(TAG2, "GId : " + arrContact.get(i).getGroupId());
				Log.d(TAG2, "Group : " + arrContact.get(i).getGroup() + "............");
			}*/
		}
		
	}
	

	public int getReceiverCount(){
		int count = 0;
		db = mHelper.getReadableDatabase();
		Cursor cursor;
		cursor = db.rawQuery("SELECT _id FROM sms", null);
		while (cursor.moveToNext()) {
			count++;
		}
		cursor.close();
		mHelper.close();

		return count;
	}

	// 수신자 목록 보기 대화상자
	private AlertDialog createDialogBox(){
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(this);
		View promptsView = li.inflate(R.layout.receiver_list, null);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);    
		mHelper = new DBHelper(this);
		db = mHelper.getReadableDatabase();
		Cursor cursor;
		SpannableStringBuilder ssb;
		int color = Color.GRAY;

		builder.setTitle("선택된 연락처 ("+receiverCount+"명)");
		builder.setView(promptsView);

		TextView textRcv = (TextView)promptsView.findViewById(R.id.textRcv);
		textRcv.setText("");

		cursor = db.rawQuery("SELECT name, phone, groupname FROM sms", null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(0);
			String phone = cursor.getString(1);
			String group = cursor.getString(2);

			ssb = new SpannableStringBuilder(name);
			ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, name.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
			if(name.length()<=2){
				textRcv.append(ssb + "       ");
			}
			else{
				textRcv.append(ssb + "   ");
			}
			textRcv.append(phone);

			//Log.d(TAG2, name + phone + group);

			if(!group.equals("")){
				textRcv.append("   ");
				ssb = new SpannableStringBuilder("(" + group + ")");
				ssb.setSpan(new ForegroundColorSpan(color), 0, group.length()+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ssb.setSpan(new AbsoluteSizeSpan(15), 0, group.length()+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textRcv.append(ssb);
			}
			textRcv.append("\n");
		}
		cursor.close();
		mHelper.close();

		builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});

		AlertDialog dialog = builder.create();

		return dialog;
	}

	// 검색 이벤트
	TextWatcher textWatcherInput = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			ListView list = (ListView)findViewById(R.id.sms_member_list);

			if(s.length()==0){ //텍스트가 다 지워질때는 전체 목록을 보여준다
				Adapter = new ContactsAdapter(SMSMemberListView.this, R.layout.sms_member, arrContact);
				list.setAdapter(Adapter);
				isSearching = false;
				Adapter.notifyDataSetChanged();
			}
			else{
				arrContactSearch.clear();
				for(int i=0; i<arrContact.size() ; i++){
					String searchData = arrContact.get(i).getName();
					String keyWord= s.toString();
					boolean isData = SoundSearcher.matchString(searchData,keyWord); //검색할 대상 , 검색 키워드로  검색키워드가 검색대상에 있으면  true를 리턴해준다
					if(isData){
						Contact temp = arrContact.get(i);
						arrContactSearch.add(temp); //검색대상에 있으면 새로운 리스트를 만들어서 이름을 애드해준다
					}
				}
				Adapter = new ContactsAdapter(SMSMemberListView.this, R.layout.sms_member, arrContactSearch);
				list.setAdapter(Adapter);
				isSearching = true;
				Adapter.notifyDataSetChanged(); //검색이 끝나면 새로운 리스트로 리스트뷰를 갱신해준다
			}
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	}; 

}